package com.uniriho.setternumber

import android.annotation.SuppressLint
import android.content.Context
import android.util.Log
import android.widget.Toast
import androidx.lifecycle.ViewModel
import com.lxr5002.lxr5002production_test.databinding.ActivitySetnumberBinding
import com.sdk.devicemanager.Barcode
import com.sdk.devicemanager.BarcodeConfig
import com.sdk.devicemanager.DEVICEcon
import com.sdk.devicemanager.ICcon

class SetNumberMoudel : ViewModel {

    private var terminalcode = ""
    private var Detonatorcode = ""
    private var deNoSub = ""
    private var mContext: Context
    private var setnumberBinding: ActivitySetnumberBinding

    constructor(mainBinding: ActivitySetnumberBinding, context: Context) {
        mContext = context
        setnumberBinding = mainBinding
    }

    @SuppressLint("SetTextI18n")
    fun initData() {
        terminalcode = getProp("persist.sys.terminalcode").trim()
        Detonatorcode = getProp("persist.sys.detonatorno").trim()
        if (terminalcode.length != 11 && !terminalcode.startsWith("DZ4")) {
            "终端编号异常".toast(mContext)
        }
        if (Detonatorcode.length != 11 && !Detonatorcode.startsWith("F")) {
            "起爆器编号异常".toast(mContext)
        }

        initBarCode()
    }

    /**
     * 检查终端编号编码规则，并写入
     */
    var pkgTemp_DeNo: String = ""

    @SuppressLint("SetTextI18n")
    fun checkDeNo():Boolean {
        pkgTemp_DeNo = setnumberBinding.editDeNo.text.toString().trim()
        Log.i("wst", "log=$pkgTemp_DeNo")
        if ("" == pkgTemp_DeNo) {
            "起爆器编号为空,请核对".toast(mContext)
            return false
        } else if (pkgTemp_DeNo.length != 11) {
            "起爆器编号必须长度为11,请核对".toast(mContext)
            return false
        } else if (!pkgTemp_DeNo.startsWith("F")) {
            "起爆器编号需以F开头，请审核".toast(mContext)
            return false
        }
        return true
    }

    /**
     * 检查起爆器编号编码规则，并写入
     */
    var pkgTemp_TerNo: String = ""

    @SuppressLint("SetTextI18n")
    fun checkTerNo():Boolean {
        pkgTemp_TerNo = setnumberBinding.editTerNo.text.toString().trim()
        Log.i("wst", "log=$pkgTemp_TerNo")
        if ("" == pkgTemp_TerNo) {
            "终端编号为空,请核对".toast(mContext)
            return false
        } else if (pkgTemp_TerNo.length != 11) {
            "终端编号必须长度为11,请核对".toast(mContext)
            return false
        } else if (!pkgTemp_TerNo.startsWith("DZ4")) {
            "终端编号需以DZ4开头，请审核".toast(mContext)
            return false
        } else if (!pkgTemp_TerNo.endsWith(deNoSub)) {
            "终端编号与终端编号未对应，请审核".toast(mContext)
            return false
        }
        return true
    }

    /**
     *
     * 检查起爆器编号和终端编号是否对应，并写入
     */
    fun checkTerNo_DeNo_write() {

        //检查起爆器编号
        if (!checkDeNo()) {
            return
        }
        //检查终端编号
        if (!checkTerNo()) {
            return
        }
        if (!pkgTemp_DeNo.endsWith(
                pkgTemp_TerNo.substring(
                    pkgTemp_TerNo.length - 6,
                    pkgTemp_TerNo.length
                )
            )
        ) {
            "起爆器编号和终端编号未对应".toast(mContext)
            return
        }

        //写起爆器编号
        if (writeDetonatorNo(pkgTemp_DeNo)) {
            "起爆器编号写入成功".toast(mContext)
            setnumberBinding.editDeNo.setText("")
        } else {
            "起爆器编号写入失败".toast(mContext)
        }

        //写终端编号
        if (writeterminalNo(pkgTemp_TerNo)) {
            "终端编号写入成功".toast(mContext)
            setnumberBinding.editTerNo.setText("")
        } else {
            "终端编号写入失败".toast(mContext)
        }
    }

    /**
     * 写入起爆器编号
     */
    fun writeDetonatorNo(value: String): Boolean {
        try {
            val mPath = "/mnt/vendor/pcie/"
            val mName = "detonatorno"
            FileUtils.writeFileO(value, mPath, mName, false)
            val detonatorno = FileUtils.readFileI(mPath, "detonatorno")
            Log.d("wst", "detonatorno=$detonatorno")
            setProp("persist.sys.detonatorno", detonatorno)
            return true
        } catch (e: Exception) {
            e.toast(mContext)
            return false
        }
    }

    /**
     * 写入起爆器编号
     */
    fun writeterminalNo(value: String): Boolean {
        try {
            val mPath = "/mnt/vendor/pcie/"
            val mName = "terminalcode"
            FileUtils.writeFileO(value, mPath, mName, false)
            val detonatorno = FileUtils.readFileI(mPath, "terminalcode")
            Log.d("wst", "terminalcode=$detonatorno")
            setProp("persist.sys.terminalcode", detonatorno)
            return true
        } catch (e: Exception) {
            e.toast(mContext)
            return false
        }
    }

    @SuppressLint("PrivateApi")
    fun getProp(key: String?): String {
        val forName = Class.forName("android.os.SystemProperties")
        val get = forName.getMethod("get", String::class.java)
        return (get.invoke(forName, key)?.toString() ?: "").trim()
    }

    @SuppressLint("PrivateApi")
    fun setProp(key: String?, value: String?) {
        try {
            val c = Class.forName("android.os.SystemProperties")
            val set = c.getMethod("set", String::class.java, String::class.java)
            set.invoke(c, key, value)
        } catch (e: Exception) {
            e.printStackTrace()
        }
    }

    fun Any.toast(context: Context, duration: Int = Toast.LENGTH_SHORT): Toast {
        return Toast.makeText(context, this.toString(), duration).apply { show() }
    }

    private var mBarcode: Barcode? = null
    private var mBarcodeConfig: BarcodeConfig? = null

    private fun initBarCode() {

        mBarcode = Barcode(mContext)
        mBarcodeConfig = BarcodeConfig()
        mBarcodeConfig!!.mOutPutMode = BarcodeConfig.OUTPUT_API
        mBarcodeConfig!!.mEncodeMode = BarcodeConfig.ENCODE_MODE_UTF8
        mBarcodeConfig!!.mTrigerMode = BarcodeConfig.TRIGGER_MODE_MANUAL
        mBarcode!!.setup1D(mBarcodeConfig)
        //打开左右键扫码
        mBarcode!!.setKeyenable(true)
    }

    fun onDestroy() {
        //关闭左右键扫码
        mBarcode!!.setKeyenable(false)
    }

    /**
     * 获取起爆器编号
     */
    @SuppressLint("SetTextI18n")
    fun getDeNo() {
        val deNo = getProp("persist.sys.detonatorno")
        if (deNo.equals("")) {
            "起爆器编号为空".toast(mContext)
        } else {
            "读取成功".toast(mContext)
            setnumberBinding.editDeNo.setText("起爆器编号：$deNo")
        }
    }

    /**
     * 获取终端编号
     */
    @SuppressLint("SetTextI18n")
    fun getTerNo() {
        val deNo = getProp("persist.sys.terminalcode")
        if (deNo.equals("")) {
            "终端编号为空".toast(mContext)
        } else {
            "读取成功".toast(mContext)
            setnumberBinding.editTerNo.setText("终端编号：$deNo")
        }
    }

    fun getSamSN(): String? {
        ICcon.getInstance().IC_ModuleOpen()
        val Card_SN = ByteArray(10)
        val Card_Type = ByteArray(128)
        val Card_ApplyInfo = ByteArray(256)
        val ret = ICcon.getInstance().SAM_Reset(Card_SN, Card_Type, Card_ApplyInfo)
        if (ret.toInt() == 0) {
            val bytesToHexString: String = DataUtils.bytesToHexString(Card_SN)
            ICcon.getInstance().IC_Close()
            return DataUtils.hexToAscii(bytesToHexString)
        }
        ICcon.getInstance().IC_Close()
        return "fail"
    }

    fun checkDeNo_write() {
        if (checkDeNo()) {
            //写起爆器编号
            if (writeDetonatorNo(pkgTemp_DeNo)) {
                "起爆器编号写入成功".toast(mContext)
                setnumberBinding.editDeNo.setText("")
            } else {
                "起爆器编号写入失败".toast(mContext)
            }
        }
    }

    fun checkTerNo_write() {
        if (checkTerNo()) {
            //写终端编号
            if (writeterminalNo(pkgTemp_TerNo)) {
                "终端编号写入成功".toast(mContext)
                setnumberBinding.editTerNo.setText("")
            } else {
                "终端编号写入失败".toast(mContext)
            }
        }
    }

    /**
     * 获取flashID
     */
    fun getFlashID(): String {
        return DEVICEcon(mContext).get_sys_parameter(1)
    }
}